package cc.mrbird.febs.common.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.baomidou.mybatisplus.core.metadata.IPage;

import cc.mrbird.febs.common.entity.FebsConstant;
import cc.mrbird.febs.common.exception.TokenInvalidException;
import cc.mrbird.febs.common.utils.TokenUtil;
import cc.mrbird.febs.system.entity.User;
import cn.hutool.core.util.ObjectUtil;
import io.jsonwebtoken.Claims;

/**
 * @author MrBird
 */
public class BaseController {

    @Resource
    protected HttpServletRequest request;

    @Resource
    protected HttpServletResponse response;

    private Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    protected User getCurrentUser() {
        return (User) getSubject().getPrincipal();
    }

    protected Session getSession() {
        return getSubject().getSession();
    }

    protected Session getSession(Boolean flag) {
        return getSubject().getSession(flag);
    }

    protected void login(AuthenticationToken token) {
        getSubject().login(token);
    }

    protected Map<String, Object> getDataTable(IPage<?> pageInfo) {
        return getDataTable(pageInfo, 2);
    }

    protected Map<String, Object> getDataTable(IPage<?> pageInfo, int dataMapInitialCapacity) {
        Map<String, Object> data = new HashMap<>(dataMapInitialCapacity);
        data.put("rows", pageInfo.getRecords());
        data.put("total", pageInfo.getTotal());
        return data;
    }

    /**
     * 根据token获取客户端用户 ID
     * @return
     */
    protected static Long getMemberIdByToken(HttpServletRequest request) {
        final String token = request.getHeader(FebsConstant.TOKEN);
        Claims claims = TokenUtil.getClaimsByToken(token);
        Long memberId = claims.get("memberId", Long.class);
        if (ObjectUtil.isNull(memberId)) {
            throw new TokenInvalidException("Token认证出错");
        }
        if (memberId <= 0) {
            throw new TokenInvalidException("Token认证出错");
        }
        return memberId;
    }
}
